<template>
  <div class="contract-page">
    <div class="container">
      <div class="form-card">
        <div class="tech-info">
          <div>{{ techInfo.realname }}：{{ techInfo.id }}</div>
          <div class="sign-status" v-if="signInfo">
            <div>
              <div
                v-if="signInfo.signer1_status === 0"
                class="sign-auth sign-status-0"
              >
                商户：等待签署
              </div>
              <div
                v-else-if="signInfo.signer1_status === 1"
                class="sign-auth sign-status-1"
              >
                商户：签署中
              </div>
              <div
                v-else-if="signInfo.signer1_status === 2"
                class="sign-auth sign-status-2"
              >
                商户：已签署
              </div>
              <div
                v-else-if="signInfo.signer1_status === 3"
                class="sign-auth sign-status-3"
              >
                商户：等待审批
              </div>
              <div
                v-else-if="signInfo.signer1_status === 4"
                class="sign-auth sign-status-4"
              >
                商户：已拒签
              </div>
            </div>
            <div style="margin: 0 10px"></div>
            <div>
              <div
                v-if="signInfo.signer2_status === 0"
                class="sign-auth sign-status-0"
              >
                平台：等待签署
              </div>
              <div
                v-else-if="signInfo.signer2_status === 1"
                class="sign-auth sign-status-1"
              >
                平台：签署中
              </div>
              <div
                v-else-if="signInfo.signer2_status === 2"
                class="sign-auth sign-status-2"
              >
                平台：已签署
              </div>
              <div
                v-else-if="signInfo.signer2_status === 3"
                class="sign-auth sign-status-3"
              >
                平台：等待审批
              </div>
              <div
                v-else-if="signInfo.signer2_status === 4"
                class="sign-auth sign-status-4"
              >
                平台：已拒签
              </div>
            </div>
          </div>
        </div>
        <!-- 步骤指示器 -->
        <div class="step-indicator">
          <div class="progress-bar" :style="{ width: widthCalc() + '%' }"></div>
          <div
            class="step"
            v-for="step in steps"
            :key="step.step"
            :style="{
              marginRight: step.step === 5 ? '-10px' : '0',
              marginLeft: step.step === 1 ? '-10px' : '0',
            }"
            :class="{ completed: counter > step.step }"
          >
            <div class="step-icon">
              <i class="fas fa-check" v-if="counter > step.step"></i>
              <span v-else>{{ step.step }}</span>
            </div>
            <div class="step-label">{{ step.label }}</div>
          </div>
        </div>

        <!-- 步骤1：上传营业执照 -->
        <div class="step-content" v-if="counter === 1" id="step-1">
          <h2 class="step-title">
            营业执照<span style="color: red; font-size: 0.8em">(必传)</span>
          </h2>
          <div class="upload-area" @click="confirm('shop_pic')">
            <div v-if="formData.shop_pic">
              <image
                class="newImage"
                :src="formData.shop_pic"
                mode="aspectFit"
              ></image>
            </div>
            <div v-else>
              <div class="upload-icon">
                <i class="fas fa-file-upload"></i>
              </div>
              <div class="upload-text">点击上传营业执照</div>
              <div class="upload-hint">
                支持 JPG、PNG 格式，文件大小不超过 5MB，请上传高清的彩色水平图片
              </div>
            </div>
          </div>
          <div v-if="formData.shop_pic">
            <input
              v-model="formData.shop_name"
              type="text"
              :disabled="isSuccess"
              id="business-code"
              style="margin-top: 20px"
              class="form-control"
              placeholder="商户名称"
            />
            <input
              v-model="formData.shop_code"
              type="text"
              id="id-number"
              :disabled="isSuccess"
              style="margin-top: 20px"
              class="form-control"
              placeholder="营业执照统一社会编号"
            />
            <input
              v-model="formData.shop_username"
              type="text"
              id="id-number"
              :disabled="isSuccess"
              style="margin-top: 20px"
              class="form-control"
              placeholder="法人姓名"
            />
          </div>
          <div class="form-actions">
            <div></div>
            <!-- 占位 -->
            <div style="width: 100%; display: flex; justify-content: center">
              <div class="btn btn-next" style="display: inline" @click="next">
                下一步
              </div>
            </div>
          </div>
        </div>

        <!-- 步骤2：上传身份证 -->
        <div class="step-content" v-else-if="counter === 2" id="step-2">
          <h2 class="step-title">
            身份证正反面<span style="color: red; font-size: 0.8em">(必传)</span>
          </h2>
          <div class="id-upload-container">
            <div class="id-upload" @click="confirm('id1_pic')">
              <div v-if="formData.id1_pic" style="width: 100%">
                <image
                  class="newImage"
                  :src="formData.id1_pic"
                  mode="aspectFit"
                ></image>
              </div>
              <div v-else>
                <div class="upload-icon">
                  <i class="fas fa-id-card"></i>
                </div>
                <div class="id-label">身份证正面</div>
                <div class="upload-hint">人像面</div>
              </div>
            </div>
            <div class="id-upload" @click="confirm('id2_pic')">
              <div v-if="formData.id2_pic" style="width: 100%">
                <image
                  class="newImage"
                  :src="formData.id2_pic"
                  mode="aspectFit"
                ></image>
              </div>
              <div v-else>
                <div class="upload-icon">
                  <i class="fas fa-id-card"></i>
                </div>
                <div class="id-label">身份证反面</div>
                <div class="upload-hint">国徽面</div>
              </div>
            </div>
          </div>
          <div v-if="formData.id1_pic">
            <input
              v-model="formData.idnum"
              type="text"
              id="id-number"
              :disabled="isSuccess"
              class="form-control"
              placeholder="法人身份证号码-自动识别"
            />
          </div>
          <div class="form-actions">
            <div class="btn btn-prev" @click="prev">上一步</div>
            <div class="btn btn-next" @click="next(2)">下一步</div>
          </div>
        </div>

        <!-- <步骤3  其他证件> -->
        <div class="step-content" v-if="counter === 3">
          <h2 class="step-title">
            技师资格证<span style="color: red; font-size: 0.8em">(必传)</span>
          </h2>
          <div class="upload-area" @click="confirm('technician_certificate')">
            <div v-if="formData.technician_certificate">
              <image
                class="newImage"
                :src="formData.technician_certificate"
                mode="aspectFit"
              ></image>
            </div>
            <div v-else>
              <div class="upload-icon">
                <i class="fas fa-file-upload"></i>
              </div>
              <div class="upload-text">点击上传技师资格证</div>
              <div class="upload-hint">
                支持 JPG、PNG 格式，文件大小不超过 5MB，请上传高清的彩色水平图片
              </div>
            </div>
          </div>

          <h2 class="step-title">
            健康证<span style="font-size: 0.8em">(非必传)</span>
          </h2>
          <div class="upload-area" @click="confirm('health_certificate')">
            <div v-if="formData.health_certificate">
              <image
                class="newImage"
                :src="formData.health_certificate"
                mode="aspectFit"
              ></image>
            </div>
            <div v-else>
              <div class="upload-icon">
                <i class="fas fa-file-upload"></i>
              </div>
              <div class="upload-text">点击上传健康证</div>
              <div class="upload-hint">
                支持 JPG、PNG 格式，文件大小不超过 5MB，请上传高清的彩色水平图片
              </div>
            </div>
          </div>

          <h2 class="step-title">
            无犯罪证明<span style="font-size: 0.8em">(非必传)</span>
          </h2>
          <div class="upload-area" @click="confirm('no_criminal_record')">
            <div v-if="formData.no_criminal_record">
              <image
                class="newImage"
                :src="formData.no_criminal_record"
                mode="aspectFit"
              ></image>
            </div>
            <div v-else>
              <div class="upload-icon">
                <i class="fas fa-file-upload"></i>
              </div>
              <div class="upload-text">点击上传无犯罪证明</div>
              <div class="upload-hint">
                支持 JPG、PNG 格式，文件大小不超过 5MB，请上传高清的彩色水平图片
              </div>
            </div>
          </div>

          <div class="form-actions">
            <div class="btn btn-prev" @click="prev">上一步</div>
            <div class="btn btn-next" @click="next">下一步</div>
          </div>
        </div>

        <!-- 步骤4：填写信息 -->
        <div class="step-content" v-if="counter === 4" id="step-3">
          <h2 class="step-title">填写企业信息</h2>
          <div class="form-group">
            <label for="business-code">商户名称</label>
            <input
              v-model="formData.shop_name"
              type="text"
              id="business-code"
              class="form-control"
              placeholder="商户名称-自动识别"
            />
          </div>
          <div class="form-group">
            <label for="business-code">营业执照统一社会编号</label>
            <input
              v-model="formData.shop_code"
              type="text"
              id="business-code"
              class="form-control"
              placeholder="营业执照统一社会编号-自动识别"
            />
          </div>
          <div class="form-group">
            <label for="legal-person">法人姓名</label>
            <input
              v-model="formData.shop_username"
              type="text"
              id="legal-person"
              class="form-control"
              placeholder="法人姓名-自动识别"
            />
          </div>
          <div class="form-group">
            <label for="id-number">身份证号码</label>
            <input
              v-model="formData.idnum"
              type="text"
              id="id-number"
              class="form-control"
              placeholder="法人身份证号码-自动识别"
            />
          </div>
          <div class="form-group">
            <label for="phone" style="color: red">手机号码</label>
            <div className="input-with-button">
              <input
                class="input"
                type="tel"
                id="phone"
                placeholder="请输入手机号码"
                required
                v-model="formData.mobile"
              />
              <div class="button" @click="getCode">
                <span v-if="!isTiming">获取验证码</span>
                <span v-if="isTiming" style="margin-left: 5px"
                  >({{ second }}s)</span
                >
                <span v-if="isTiming">重新获取</span>
              </div>
            </div>
          </div>
          <div class="form-group">
            <label for="id-number" style="color: red">验证码</label>
            <input
              v-model="mobile_code"
              type="text"
              id="id-number"
              class="form-control"
              placeholder="请输入手机验证码"
            />
          </div>
          <div class="form-actions">
            <div class="btn btn-prev" @click="prev">上一步</div>
            <div class="btn btn-next" @click="next('validate')">下一步</div>
          </div>
        </div>

        <!-- 步骤4：选择签约模式 -->
        <div class="step-content" v-if="counter === 5" id="step-4">
          <h2 class="step-title">选择签约模式</h2>
          <div class="sign-mode-options">
            <div
              class="sign-mode-option"
              :class="{ active: formData.sign_type === 1 }"
              @click="formData.sign_type = 1"
            >
              <div class="sign-mode-icon">
                <i class="fas fa-laptop"></i>
              </div>
              <div class="sign-mode-title">线上签约</div>
              <div class="sign-mode-desc">全程在线完成，方便快捷</div>
            </div>
            <div
              class="sign-mode-option"
              :class="{ active: formData.sign_type === 0 }"
              @click="formData.sign_type = 0"
            >
              <div class="sign-mode-icon">
                <i class="fas fa-handshake"></i>
              </div>
              <div class="sign-mode-title">线下签约</div>
              <div class="sign-mode-desc">专业人员上门服务</div>
            </div>
          </div>
          <div class="form-actions">
            <div class="btn btn-prev" @click="prev">上一步</div>
            <div class="btn btn-submit" @click="submit">提交申请</div>
          </div>
        </div>

        <div v-if="counter === 6">
          <!-- 提交成功 -->
          <h2 class="step-title">提交成功！</h2>
          <p style="text-align: center; color: green; font-size: 18px">
            感谢您的申请；请注意接收签约短信。
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { request } from "../../common/api";
import { config } from "../../common/config";

const counter = ref(1);
const techInfo = ref({});
const signInfo = ref({});
const mobile_code = ref("");
const isTiming = ref(false);
const second = ref(60);
const formData = ref({
  shop_pic: "",
  id1_pic: "",
  id2_pic: "",
  shop_name: "",
  shop_code: "",
  shop_username: "",
  idnum: "",
  mobile: "",
  sign_type: 1, // 1线上 0线下
  technician_certificate: "", //技师资格证图片地址
  health_certificate: "", //健康证图片地址
  no_criminal_record: "", //无犯罪证明图片地址
});

const widthCalc = () => {
  if ((counter.value - 1) * 25 > 100) {
    return 100;
  }
  return (counter.value - 1) * 25;
};

const isSuccess = computed(() => {
  if (
    signInfo.value &&
    ([2, 3].includes(signInfo.value.signer1_status) ||
      [1, 2, 3].includes(signInfo.value.signer2_status))
  ) {
    return true;
  }
  return false;
});

const steps = [
  { step: 1, label: "营业执照" },
  { step: 2, label: "身份证" },
  { step: 3, label: "其他证件" },
  { step: 4, label: "信息填写" },
  { step: 5, label: "签约模式" },
];

const next = (val) => {
  // console.log(val);

  if (isSuccess.value && val === 3) {
    uni.showToast({
      title: "您已提交申请，无法修改",
      icon: "none",
    });
    return;
  }
  if (val === "validate") {
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(formData.value.mobile)) {
      uni.showToast({
        title: "请输入正确的手机号",
        icon: "none",
      });
      return;
    } else if (!mobile_code.value) {
      uni.showToast({
        title: "请填写手机验证码",
        icon: "none",
      });
      return;
    }
  } else if (counter.value === 1) {
    if (!formData.value.shop_pic) {
      return uni.showToast({
        title: "请上传营业执照",
        icon: "none",
      });
    } else if (
      !formData.value.shop_name ||
      !formData.value.shop_code ||
      !formData.value.shop_username
    ) {
      return uni.showToast({
        title: "请填写完整营业执照信息",
        icon: "none",
      });
    }
  } else if (counter.value === 2) {
    if (!formData.value.id1_pic || !formData.value.id2_pic) {
      return uni.showToast({
        title: "请上传身份证正反面",
        icon: "none",
      });
    } else if (!formData.value.idnum) {
      return uni.showToast({
        title: "请填写完整身份证信息",
        icon: "none",
      });
    }
  } else if (counter.value === 3) {
    if (!formData.value.technician_certificate) {
      return uni.showToast({
        title: "请上传技师资格证",
        icon: "none",
      });
    }
  }

  if (counter.value < 5) {
    counter.value++;
  }
};

const prev = () => {
  if (counter.value > 1) {
    counter.value--;
  }
};

const getCode = () => {
  if (!formData.value.mobile) {
    uni.showToast({
      title: "请填写手机号码",
      icon: "error",
    });
    return;
  }
  if (isTiming.value) return;
  isTiming.value = true;
  second.value = 60;
  const timer = setInterval(() => {
    second.value--;
    if (second.value <= 0) {
      clearInterval(timer);
      isTiming.value = false;
    }
  }, 1000);

  request({
    url: "login/smsCode",
    method: "POST",
    data: { mobile: formData.value.mobile },
  }).then((res) => {
    uni.showToast({
      title: "验证码已发送",
      icon: "success",
    });
  });
};

// 上传照片、营业执照、身份证
const imageClick = () => {
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      count: 6, //默认9
      sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
      success: function (res) {
        uni.showLoading({
          title: "loading...",
          mask: true,
        });
        uni.uploadFile({
          url: config.URL + "/index/uploadImage",
          filePath: res.tempFilePaths[0],
          name: "file",
          header: {
            token: uni.getStorageSync("token"),
          },
          success: (res) => {
            const _data = JSON.parse(res.data);
            if (_data.code == 1) {
              resolve(_data.data);
            }
          },
          fail(err) {
            reject(err);
          },
          complete() {
            uni.hideLoading();
          },
        });
      },
    });
  });
};

// 营业执照
const shopOcr = (image) => {
  request({
    url: "index/get_businessLicense",
    method: "POST",
    data: { businessLicense_file: image },
  })
    .then((res) => {
      formData.value.shop_name = res.name;
      formData.value.shop_code = res.reg_num;
      formData.value.shop_username = res.person;
    })
    .catch((err) => {
      uni.showToast({
        title: "请上传的正确的营业执照",
        icon: "none",
      });
    })
    .finally(() => {
      uni.hideLoading();
    });
};

// 身份证、正面
const idOcr = (image, type) => {
  request({
    url: "index/get_id_card",
    method: "POST",
    data: { id_card_file: image, side: type },
  })
    .then((res) => {
      if (type === "face") {
        formData.value.idnum = res.num;
      }
    })
    .catch((err) => {
      if (type === "face") {
        uni.showToast({
          title: "未识别到正确的身份证信息",
          icon: "none",
        });
      }
    })
    .finally(() => {
      uni.hideLoading();
    });
};

const confirm = (type) => {
  if (isSuccess.value) {
    uni.showToast({
      title: "您已提交申请，无法修改",
      icon: "none",
    });
    return;
  }
  imageClick().then((images) => {
    uni.showLoading({
      title: "照片检测中...",
    });
    if (type === "shop_pic") {
      shopOcr(images);
      formData.value.shop_pic = images;
    } else if (type === "id1_pic") {
      idOcr(images, "face");
      formData.value.id1_pic = images;
    } else if (type === "id2_pic") {
      idOcr(images, "back");
      formData.value.id2_pic = images;
    } else if (type === "technician_certificate") {
      formData.value.technician_certificate = images;
      uni.hideLoading();
    } else if (type === "health_certificate") {
      formData.value.health_certificate = images;
      uni.hideLoading();
    } else if (type === "no_criminal_record") {
      formData.value.no_criminal_record = images;
      uni.hideLoading();
    }
  });
};

const submit = () => {
  uni.showLoading({
    title: "提交中...",
    mask: true,
  });
  request({
    url: "index/go_sign",
    method: "POST",
    data: {
      ...formData.value,
      tech_id: techInfo.value.id,
      mobile_code: mobile_code.value,
    },
  })
    .then((res) => {
      if (res.code == -1) {
        uni.showToast({
          title: res.msg || "提交失败，请稍后重试",
          icon: "none",
        });
      } else {
        counter.value = 6;
        uni.showToast({
          title: "申请已提交！",
          icon: "success",
        });
      }
    })
    .catch((err) => {
      uni.showToast({
        title: err.msg || "服务器错误",
        icon: "none",
      });
    })
    .finally(() => {
      uni.hideLoading();
    });
};

const getTechInfo = () => {
  request({
    url: "index/index",
    method: "POST",
  }).then((res) => {
    techInfo.value = res.data.technician;
    getSignInfo(techInfo.value.id);
  });
};

const getSignInfo = (id) => {
  request({
    url: "index/get_signinfo",
    method: "POST",
    data: { tech_id: id },
  }).then((res) => {
    signInfo.value = res.data;
    if (res.data) {
      formData.value.mobile = signInfo.value.mobile;
      formData.value.shop_username = signInfo.value.shop_username;
      formData.value.idnum = signInfo.value.shop_idnum;
      formData.value.shop_name = signInfo.value.shop_name;
      formData.value.shop_code = signInfo.value.shop_code;
      formData.value.id1_pic = signInfo.value.id1_pic;
      formData.value.id2_pic = signInfo.value.id2_pic;
      formData.value.shop_pic = signInfo.value.shop_pic;
    }
  });
};

onLoad(() => {
  const token = uni.getStorageSync("token");
  if (!token) {
    uni.navigateTo({
      url: "/pages/login/index",
    });
  } else {
    getTechInfo();
  }
});
</script>

<style lang="scss">
@import url("./index.scss");
</style>
